package controller;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.activemq.ActiveMQConnection;

import domain.Mission;

/**
 * Servlet implementation class MissionServlet
 */
@WebServlet("/mission")
public class MissionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public MissionServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		ActiveMQConnection connection;
		try {
			connection = ActiveMQConnection
					.makeConnection("tcp://localhost:61616");

			connection.start();
			Session session = connection.createSession(false,
					Session.AUTO_ACKNOWLEDGE);

			Destination destination = session
					.createQueue("swarch.mission.input");
			TextMessage simpleMessage = session.createTextMessage();
			simpleMessage.setText("<message-type>Mission</message-type>");

			MessageProducer producer = session.createProducer(destination);
			producer.send(simpleMessage);
			System.out.println("send message");

			MessageConsumer consumer = session.createConsumer(session
					.createQueue("swarch.mission.output"));

			ObjectMessage missionMessage = (ObjectMessage) consumer
					.receive(1000);
			ArrayList<Mission> missionList = (ArrayList<Mission>) missionMessage
					.getObject();

			request.setAttribute("missionList", missionList);
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		request.setAttribute("a", "A");
		RequestDispatcher dispatcher = getServletContext()
				.getRequestDispatcher("/mission/index.jsp");
		dispatcher.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}
}
